import { defineStore } from 'pinia';
import router from '../router';

export const useLoginUserStore = defineStore('loginUserStore', {
  state: () => ({
    isAuthenticated: false,  // 是否已登录
    token: '',//token
    currentUser: {
      id:'',
      orgId: '',
      orgName: '',
      menuList: []
    },       // 初始状态为 null，表示没有用户登录
  }),
  actions: {
    loginUser(user: any, token: string) {
      if (user != null) {
        this.currentUser = user;
        this.token = token;
        this.isAuthenticated = true;
        this.dynamicRoutes();
      } else {
        this.isAuthenticated = false;
      }
    },
    logoutUser() {
      this.isAuthenticated = false;
      this.currentUser = { menuList: [] };
      this.token = '';
    },
    dynamicRoutes() {
      const mainRoute = router.options.routes.find(route => route.name === 'MainForm');
      if (this.currentUser.menuList) {
        this.currentUser.menuList.forEach((menu: {url, childMenuList: any[]; }) => {
          //子项
          if (menu.childMenuList && menu.childMenuList.length > 0) {
            this.addRoutes(menu.childMenuList, mainRoute);
          }
          else if(menu.url)//没有子项，有url地址
          {
            const urls = menu.url.split("/");
            const route = {
              path: urls[urls.length - 1],
              name: urls[urls.length - 1],
              component: () => import(`/src/views/${menu.url}.vue`),
              meta: { requiresAuth: true },
            };
            mainRoute.children = mainRoute.children || [];
            mainRoute.children.push(route);
          }
        });
      }
    },
    addRoutes(menuList: any, parentRoute: any) {
      menuList.forEach((item: { url: string; childMenuList: any[]; }) => {
        if (item.url) {
          const urls = item.url.split("/");
          const route = {
            path: urls[urls.length - 1],
            name: urls[urls.length - 1],
            component: () => import(`/src/views/${item.url}.vue`),
            meta: { requiresAuth: true },
          };
          parentRoute.children = parentRoute.children || [];
          parentRoute.children.push(route);
        }
        if (item.childMenuList && item.childMenuList.length > 0) {
          this.addRoutes(item.childMenuList, parentRoute);
        }
      });

      router.addRoute(parentRoute);
    },
  },
  persist: {
    key: 'useLoginUserStore', // 存储的 key
    storage: window.sessionStorage, // 使用 localStorage
    paths: ['isAuthenticated', 'currentUser', 'token'], // 需要持久化的字段
  }
});
